package com.coder4j.starter.mybatis.provider;

import com.alibaba.fastjson.JSON;
import com.coder4j.starter.tools.util.StringUtils;

import java.util.ArrayList;

public class BatchUpdateProvider {

    public static String updateList(BatchUpdateProviderVO vo){
        StringBuilder builder = new StringBuilder();
        builder.append("<script>")
                .append("<foreach collection='list' item='item' separator=';'>")
                .append(" UPDATE ")
                .append(vo.getTableName())
                .append(" SET ");

        for (String javaField : vo.getJavaFields()) {
            String sqlField = StringUtils.humpToLine(javaField);
            builder.append(sqlField)
                    .append("=#{item.")
                    .append(javaField)
                    .append("},");
        }
        builder.deleteCharAt(builder.length() - 1);

        builder.append(" WHERE id = #{item.id} ")
                .append(" </foreach> ")
                .append("</script>");

        return builder.toString();
    }

    // {"id":1,"userName":"张三","age":23}
    public static void main(String[] args) {
        BatchUpdateProviderVO vo = new BatchUpdateProviderVO("test_1");
        vo.setList(new ArrayList(){{
            add(JSON.parse("{\"id\":1,\"userName\":\"张三\",\"age\":23}"));
            add(JSON.parse("{\"id\":2,\"userName\":\"李四\",\"age\":24}"));
        }});
        vo.setFields("userName","age");

        String sqlStr = BatchUpdateProvider.updateList(vo);
        System.out.println(sqlStr);
    }
}
